<template>
  <!-- 满屏容器：自动铺满、可滚动 -->
  <div
    class="usage-table-wrap"
    :class="{ full: fullHeight }"
    :style="wrapStyle"
  >
  <el-table
      :data="displayedItems"             
      :row-key="rowKey"
      class="usage-table"
      border
      stripe
      size="small"
      highlight-current-row
      :height="tableHeight"
      :header-cell-style="headerCellStyle"
      :cell-style="cellStyle"
      :default-sort="defaultSort"
    >
      <!-- 名称 / 概览列 -->
      <!-- <el-table-column
        label="名称 / 概览"
        min-width="220"
        show-overflow-tooltip
      >
        <template #default="{ row }">
          <div class="name-cell">
            <div class="avatar" :style="{ background: avatarBg(row.status) }">
              {{ initials(row.assetName) }}
            </div>
            <div class="meta">
              <div class="name" :title="row.assetName">{{ row.assetName || '-' }}</div>
              <div class="sub">设备使用信息</div>
            </div> 
          </div>
        </template>
      </el-table-column> -->

      <!-- 启用时间 -->
      <el-table-column
        prop="enabledAt"
        label="启用时间"
        min-width="120"
        sortable
        :sort-method="(a,b) => dateSort(a.enabledAt,b.enabledAt)"
      >
        <template #default="{ row }">
          {{ fmtDate(row.enabledAt) }}
        </template>
      </el-table-column>

     
      <el-table-column prop="department" label="使用部门" min-width="150" show-overflow-tooltip>
  <template #header>
    <div class="dept-header">
      <span>使用部门</span> 
      <el-select
        v-model="deptToken"
        class="dept-select"
        filterable
        allow-create
        default-first-option
        clearable
        placeholder="选择或输入关键字"
      >
        <el-option v-for="opt in deptOptions" :key="opt" :label="opt" :value="opt" />
      </el-select>
    </div>
  </template>

  <template #default="{ row }">
    <span>{{ showDept(row.department) }}</span>
    <el-tag v-if="row.__firstUse" size="small" type="success" effect="plain" class="ml6">首</el-tag>
  </template>
</el-table-column>





      <!-- 使用时间段 --> 
      <el-table-column
        prop="useRange"
        label="使用时间段"
        min-width="180"
        :formatter="formatterIf(0, r => fmtRange(r.useRange))"
      />

      <!-- 闲置时间段 -->
      <el-table-column
        prop="idleRange"
        label="闲置时间段"
        min-width="180"
        :formatter="formatterIf(2, r => fmtRange(r.idleRange))"
      />

      <!-- 停用时间 -->
      <el-table-column
        prop="stopAt"
        label="停用时间"
        min-width="180"  
        :formatter="formatterIf(3, r => fmtRange(r.stopAt))"
      /> 
      <!-- 当前状态（纯图标+文字，便于筛选/排序） -->
      <el-table-column
        prop="status"
        label="当前情况"
        width="120"
        sortable 
      >
        <template #default="{ row }">
          <div class="status-cell">
            <i class="dot" :style="{ background: statusNowDot(row.now_status) }"></i>
            <span>{{ statusNowLabel(row.status,row.now_status) }}</span>
          </div>
        </template>
      </el-table-column>

      <!-- 空态 -->
      <template #empty>
        <el-empty description="暂无设备数据" />
      </template>
    </el-table>
  </div>
</template>

<script setup>
import { ref, computed } from 'vue'
import { Calendar, OfficeBuilding, Clock, Timer, CircleClose } from '@element-plus/icons-vue'
import { useStatusGuard } from '@/api/sbtz/useStatusGuard'
const { formatterIf } = useStatusGuard()

const props = defineProps({
  items:      { type: Array, default: () => [] },
  fullHeight: { type: Boolean, default: true },
  height:     { type: [Number, String], default: null },
  cardMin:    { type: [Number, String], default: 360 },
  gap:        { type: Number, default: 16 },
  padding:    { type: Number, default: 16 },
})
console.log(props.items);
/** —— 工具 —— */
const px = v => (typeof v === 'number' ? `${v}px` : String(v))
const rowKey = row => row.id ?? row.assetName ?? Math.random().toString(36).slice(2)

 
// ✅ 判定部门值是否有效
const INVALID_DEPT = new Set(['', '0', '-', '—', 'null', 'undefined'])
const isValidDept = (v) => {
  const s = String(v ?? '').trim()
  return s && !INVALID_DEPT.has(s.toLowerCase())
}

// 单选关键字
const deptToken = ref('')

// 下拉选项：只聚合“有效”的部门
const deptOptions = computed(() => {
  const set = new Set()
  const src = Array.isArray(props.items) ? props.items : []
  for (const r of src) {
    const dep = String(r?.department ?? '').trim()
    if (isValidDept(dep)) set.add(dep)
  }
  return [...set].sort((a, b) => a.localeCompare(b))
})

// 表格显示的数据：当选择为无效值（空/0等）时，不做筛选
const displayedItems = computed(() => {
  const src = Array.isArray(processedItems?.value) ? processedItems.value : []
  const tokenRaw = String(deptToken.value ?? '').trim()
  if (!isValidDept(tokenRaw)) return src  // ← 直接展示全部
  const token = tokenRaw.toLowerCase()
  return src.filter(r => String(r?.department ?? '').toLowerCase().includes(token))
})

// 显示用：把无效部门渲染成 "—"
const showDept = (dep) => (isValidDept(dep) ? dep : '—')



function fmtDate(d) {
  if (!d) return '-'
  const t = new Date(d)
  if (Number.isNaN(t.getTime())) return '-'
  const y = t.getFullYear()
  const m = String(t.getMonth() + 1).padStart(2, '0')
  const day = String(t.getDate()).padStart(2, '0')
  return `${y}-${m}-${day}`
}
function fmtTime(d) {
  if (!d) return '--:--'
  const t = new Date(d)
  if (Number.isNaN(t.getTime())) return '--:--'
  const h = String(t.getHours()).padStart(2, '0')
  const m = String(t.getMinutes()).padStart(2, '0')
  return `${h}:${m}`
}

function parseDate(d) {
  if (!d) return null
  const t = d instanceof Date ? d
    : new Date(String(d).replace(/-/g,'/').replace('T',' ').replace(/Z$/,''))
  return Number.isNaN(t.getTime()) ? null : t
}

function fmtDateOnly(d) {
  const t = parseDate(d)
  if (!t) return '-'
  const y = t.getFullYear()
  const m = String(t.getMonth()+1).padStart(2,'0')
  const day = String(t.getDate()).padStart(2,'0')
  return `${y}-${m}-${day}`
}

// 如果要到“时分秒”，用这个；想只到“天”就用上面的 fmtDateOnly
function fmtDateTime(d) {
  const t = parseDate(d)
  if (!t) return '-'
  const y = t.getFullYear()
  const m = String(t.getMonth()+1).padStart(2,'0')
  const day = String(t.getDate()).padStart(2,'0')
  const h = String(t.getHours()).padStart(2,'0')
  const mi = String(t.getMinutes()).padStart(2,'0')
  const s = String(t.getSeconds()).padStart(2,'0')
  return `${y}-${m}-${day} ${h}:${mi}:${s}`
}

// ✅ 这里控制：end 为空时显示“今”
function fmtRange(r, { full = false } = {}) {
  if (!r || (!r.start && !r.end)) return '-'
  const fmt = full ? fmtDateTime : fmtDateOnly
  const start = r.start ? fmt(r.start) : '-'
  // 没有 end（或 end 在将来）→ 显示“今”
  let end
  if (!r.end) end = '今'
  else {
    const et = parseDate(r.end)
    end = et && et.getTime() > Date.now() ? '今' : fmt(r.end)
  }
  return `${start} ~ ${end}`
}

const isIdle = (s) => {
  if (s == null) return false
  if (typeof s === 'string') {
    const v = s.trim().toLowerCase()
    return v === '2' || v === 'idle'
  }
  return Number(s) === 2
}


function initials(name) {
  if (!name) return '设'
  const s = String(name).trim()
  return s.length <= 2 ? s : s.slice(0, 2)
}
function statusLabel(s) {
  return ({ 0: '使用', 1: '待修', 2: '闲置', 3: '退役' ,4: '改造' }[s] || '未知')   
}

// function statusNowLabel(status,now_status) {
//   return ({ 0: '使用中', 2: '停用'}[s] || '未知')   
// }

/**
 * @param {number|string} status     0=使用, 1=待修, 2=闲置, 3=退役, 4=改造
 * @param {number|string} now_status 1=当前状态，其它=历史/结束
 */
 function statusNowLabel(status, now_status) { 
  const s = Number(status);
  const now = Number(now_status) === 1;
  console.log(now_status,s,now);

  const base = { 0: '使用', 1: '待修', 2: '闲置', 3: '退役', 4: '改造' };
  const label = base[s];
  if (!label) return '未知';

  return now  ? `${label}中` : '停用';
}


function statusTagType(s) {
  return ({ 0: 'success', 1: 'warning',2: 'warning', 3: 'danger', 4: 'warning' }[s] || 'info')
}
function headBg(s) { // 仍可复用（目前未在表格使用）
  return ({
    active: 'linear-gradient(90deg, #67c23a, #95d475)',
    idle: 'linear-gradient(90deg, #e6a23c, #f3d19e)',
    stopped: 'linear-gradient(90deg, #f56c6c, #fab6b6)'
  }[s] || 'linear-gradient(90deg, #909399, #c8c9cc)')
}
function avatarBg(s) {
  return ({
    active: 'linear-gradient(135deg, #ecfdf5, #e8fff1)',
    idle: 'linear-gradient(135deg, #fff8e6, #fff2d8)',
    stopped: 'linear-gradient(135deg, #fff0f0, #ffe6e6)',
  }[s] || '#eef2ff')
}
function statusDot(s) {
  return ({
    0: '#67c23a',
    1: '#e6a23c',
    2: '#e6a23c',
    4: '#e6a23c', 
    3: '#f56c6c',
  }[s] || '#909399')
}
function statusNowDot(s) {
  return ({
    0: '#e6a23c',
    1: '#67c23a', 
  }[s] || '#909399')
}
const statusOrder = s => ({ active: 1, idle: 2, stopped: 3 }[s] ?? 9)
const dateSort = (a, b) => {
  const ta = a ? new Date(a).getTime() : 0
  const tb = b ? new Date(b).getTime() : 0
  return (ta || 0) - (tb || 0)
}

/** —— 布局样式 —— */
const wrapStyle = computed(() => {
  const style = { padding: px(props.padding), overflow: 'auto' }
  if (props.height != null) {
    style.height = px(props.height)
  }
  return style
})

/** 给 el-table 的高度：传数字时启用固定表头；否则自适应 */
const tableHeight = computed(() => {
  if (typeof props.height === 'number') return props.height - props.padding * 2
  if (/^\d+$/.test(String(props.height))) return Number(props.height) - props.padding * 2
  return null // 未指定，自动撑开
})

/** —— 表样式（更企业化） —— */
const headerCellStyle = () => ({
  background: 'linear-gradient(180deg, #fafafa, #f3f4f6)',
  color: '#344054',
  fontWeight: 700,
  borderColor: '#eef0f3',
})
const cellStyle = () => ({
  color: '#1f2937',
  borderColor: '#f1f2f5',
})
const defaultSort = { prop: 'enabledAt', order: 'descending' }


// 取一条记录的“排序时间”：优先 createdAt，其次 enabledAt，再其次 useRange.start
function firstUseTime(row) {
  const c = parseDate(row.createdAt)
  const e = parseDate(row.enabledAt)
  const u = parseDate(row?.useRange?.start)
  const t = c ?? e ?? u
  return t ? t.getTime() : Number.POSITIVE_INFINITY // 没时间的排到最后
}

/** 处理后的表格数据：给每条记录打上 __firstUse 标记 */
const processedItems = computed(() => {
  const src = Array.isArray(props.items) ? props.items : [];
  const n = src.length;
  if (n === 0) return [];

  const depStat = new Map(); // dep -> { count, minTime, minKey, idx }
  const out = new Array(n);

  // 统一取比较键与时间戳（只算一次）
  const getKey = (r) => (r.id ?? r.assetName ?? '');
  const firstUseTs = (r) => {
    const parse = (d) => {
      if (!d) return Number.POSITIVE_INFINITY;
      const t = new Date(d);
      return isNaN(t) ? Number.POSITIVE_INFINITY : t.getTime();
    };
    const c = parse(r.createdAt);
    const e = parse(r.enabledAt);
    const u = r?.useRange?.start ? parse(r.useRange.start) : Number.POSITIVE_INFINITY;
    return Math.min(c, e, u);
  };

  // pass1: 统计每个部门的“最早记录索引”
  for (let i = 0; i < n; i++) {
    const r = src[i];
    const dep = r.department;
    const t = firstUseTs(r);
    const k = getKey(r);

    out[i] = { ...r, __firstUse: false }; // 复制一份并默认 false

    if (!dep) continue;
    const s = depStat.get(dep);
    if (!s) {
      depStat.set(dep, { count: 1, minTime: t, minKey: k, idx: i });
    } else {
      s.count++;
      if (t < s.minTime || (t === s.minTime && String(k) < String(s.minKey))) {
        s.minTime = t;
        s.minKey = k;
        s.idx = i;
      }
    }
  }

  // pass2: 把每个部门“最早的那条”标为 true
  depStat.forEach((s) => {
    if (s.count === 1) {
      out[s.idx].__firstUse = true;
    } else {
      out[s.idx].__firstUse = true;
    }
  });

  return out;
});








</script>

<style scoped>
/* —— 外层容器 —— */
.usage-table-wrap.full {
  height: 100%;
  display: flex;
  flex-direction: column;
}
.usage-table {
  border-radius: 14px;
  overflow: hidden;
  box-shadow: 0 10px 28px rgba(0,0,0,.05);
  --row-padding-y: 10px;
}

/* —— 名称单元格 —— */
.name-cell {
  display: flex;
  align-items: center;
  gap: 12px;
  min-height: 44px;
}
.name-cell .avatar {
  width: 36px; height: 36px;
  border-radius: 10px;
  display: grid; place-items: center;
  font-weight: 700;
  color: #334155;
  box-shadow: inset 0 0 0 1px rgba(0,0,0,.04);
}
.name-cell .meta { min-width: 0; flex: 1 1 auto; }
.name-cell .meta .name {
  font-weight: 700; font-size: 14px;
  white-space: nowrap; overflow: hidden; text-overflow: ellipsis;
}
.name-cell .meta .sub {
  font-size: 12px; color: #94a3b8; margin-top: 2px;
}
.name-cell .status-tag {
  margin-left: auto;
}
.status-cell {
  display: inline-flex; align-items: center; gap: 8px;
  font-weight: 600;
}
.dot {
  width: 8px; height: 8px; border-radius: 50%;
  display: inline-block;
}

/* —— 表格细节优化 —— */
:deep(.el-table) {
  --el-table-header-text-color: #344054;
  --el-table-row-hover-bg-color: #f8fafc;
  --el-table-border-color: #eef0f3;
  --el-table-current-row-bg-color: #eff6ff;
}
:deep(.el-table .el-table__cell) {
  padding-top: var(--row-padding-y);
  padding-bottom: var(--row-padding-y);
}

/* 自定义滚动条（更企业化） */
.usage-table-wrap::-webkit-scrollbar { width: 10px; height: 10px; }
.usage-table-wrap::-webkit-scrollbar-thumb {
  background: rgba(60,60,67,.18);
  border-radius: 6px;
}
.usage-table-wrap::-webkit-scrollbar-track { background: transparent; }

.ml6 { margin-left: 6px; }


.dept-header{ display:flex; align-items:center; gap:8px; }
.dept-select{ width:72px;} 
</style>
